package main

import (
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"

	"gitee.com/dinglz/dingapi/dinglog"
	"github.com/gorilla/mux"
)

var (
	wd   string
	port *string
)

func init() {
	port = flag.String("port", "80", "start_port")
	flag.Parse()
}

func main() {
	dinglog.Info("正在启动dingMarkdown编辑器")
	wd, _ := os.Getwd()
	mymux := mux.NewRouter()
	apimux := mymux.PathPrefix("/api").Subrouter()
	apimux.HandleFunc("/savemd", func(w http.ResponseWriter, r *http.Request) {
		text := r.FormValue("md")
		ioutil.WriteFile(wd+"/text.md", []byte(text), 0666)
		fmt.Fprint(w, "ok")
	})
	apimux.HandleFunc("/getmd", func(w http.ResponseWriter, r *http.Request) {
		_, isok := os.Stat(wd + "/text.md")
		if isok != nil {
			fmt.Fprint(w, "")
			return
		}
		res, _ := ioutil.ReadFile(wd + "/text.md")
		fmt.Fprint(w, string(res))
	})
	apimux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
		file, openerr := os.Open(wd + "/text.md")
		if openerr != nil {
			fmt.Fprint(w, "请先保存一个文件！")
			return
		}
		defer file.Close()
		filehander := make([]byte, 512)
		file.Read(filehander)
		filestat, _ := file.Stat()
		w.Header().Set("Content-Disposition", "attachment; filename="+"text.md")
		w.Header().Set("Content-Type", http.DetectContentType(filehander))
		w.Header().Set("Content-Length", strconv.FormatInt(filestat.Size(), 10))
		file.Seek(0, 0)
		io.Copy(w, file)
	})
	mymux.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir(wd+"/dist"))))
	myserver := http.Server{
		Addr:    "0.0.0.0:" + *port,
		Handler: mymux,
	}
	err := myserver.ListenAndServe()
	if err != nil {
		dinglog.Error("服务器启动失败:" + err.Error())
	}
}
